<template>
  <div class="monthPlanAdd">
    <b-table
      ref="table"
      bordered
      :scroll="{ x: 1600 }"
      :columns="columns"
      :request="loadData"
      :export-config="{use:true,select:'云筑网合同入库采购明细选中',all:'云筑网合同入库采购明细全部'}"
    >
      <template
        v-if="state !== 3"
        slot="prefix"
        slot-scope="ref"
      >
        <a-button
          type="primary"
          @click="openDailog"
        >
          添加行
        </a-button>
        <a-button @click="ref.delete(delFuc)">
          删除行
        </a-button>
      </template>
      <span
        slot="index"
        slot-scope="text, record, index"
      >{{ index + 1 }}</span>
      <template
        v-for="col in ['number', 'settlePrice', 'contractPrice','yunzhuRemark']"
        :slot="col"
        slot-scope="text, record, index"
      >
        <div :key="col">
          <template v-if="index === editingIndex">
            <BaseInput
              v-if="col === 'yunzhuRemark'"
              v-model="record.yunzhuRemark"
            />
            <BaseInputNumber
              v-else-if="col === 'settlePrice' || col === 'contractPrice'"
              v-model="record[col]"
              :precision="2"
              @blur="handleChange($event.target.value, record, col)"
            />
            <BaseInputNumber
              v-else
              v-model="record[col]"
              :precision="3"
              @blur="handleChange($event.target.value, record, col)"
            />
          </template>
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <template
        slot="operation"
        slot-scope="text, record, index"
      >
        <div class="editable-row-operations">
          <span v-if="index === editingIndex && state !== 3">
            <a @click="() => save(record)">保存</a>
            <a @click="cancel(record.id)">取消</a>
          </span>
          <span v-else>
            <a
              :disabled="editingIndex !== null || state === 3"
              @click="editingIndex = index"
            >编辑</a>
          </span>
        </div>
      </template>
    </b-table>
    <material-list
      ref="detailDialog"
      @createList="createList"
    />
  </div>
</template>
<script>
import cloudBuildNetworkApi from '@/api/legal/branchContract/cloudBuildNetwork'

const data = []
const columns =[
                {
                    title: '序号',
                    scopedSlots: { customRender: 'index' },
                    fixed: 'left',
                    width: 70
                },
                {
                    title: '物资名称',
                    dataIndex: 'materialName',
                    fixed: 'left',
                    width: 100
                },
                {
                    title: '物料编码',
                    dataIndex: 'materialCode',
                    width: 180
                },
                {
                    title: '规格型号',
                    dataIndex: 'materialModel',
                    width: 100
                },
                {
                    title: '单位',
                    dataIndex: 'materialUnit',
                    width: 100
                },
                {
                    title: '数量',
                    dataIndex: 'number',
                    width: 150,
                    scopedSlots: { customRender: 'number' }
                },

                {
                    title: '发包人结算单价',
                    dataIndex: 'settlePrice',
                    scopedSlots: { customRender: 'settlePrice' },
                    width: 150
                },
                {
                    title: '发包人结算金额',
                    dataIndex: 'sumSettle',
                    width: 150
                },
                {
                    title: '合同单价',
                    dataIndex: 'contractPrice',
                    scopedSlots: { customRender: 'contractPrice' },
                    width: 150
                },
                {
                    title: '合同金额',
                    dataIndex: 'sumTotal',
                    width: 100
                },
                {
                    title: '结算单价与合同单价差',
                    dataIndex: 'sumSettlContractDiff',
                    width: 180
                },
                {
                    title: '结算金额与合同金额差',
                    dataIndex: 'sumSettleContract',
                    width: 180
                },
                {
                    title: '价差比例',
                    dataIndex: 'sumUnitPoint',
                    width: 140
                },
                {
                    title: '备注',
                    dataIndex: 'yunzhuRemark',
                    scopedSlots: { customRender: 'yunzhuRemark' },
                    width: 140
                },
                {
                    title: '操作',
                    dataIndex: 'operation',
                    scopedSlots: { customRender: 'operation' },
                    fixed: 'right',
                    width: 140
                }
            ]
export default {
  name:'a'+Date.now(),
  props: {
        state: {
            type: Number
        },
        id: {
            type: String
        }
    },
    data() {
        this.cacheData = data.map(item => ({ ...item }))
        return {
            editingIndex: null,
            columns: columns.filter(item => this.state !== 3 || this.state === 3 && item.dataIndex !== 'operation'),
            editingKey: '',
            loadData: (params) => {
                params.id = this.id
                let searchData = Object.assign(params, this.queryParam)
                return cloudBuildNetworkApi.findListByDetails({}, searchData)
            },
            delFuc: cloudBuildNetworkApi.deleteByDetails,
            rules: {
                number: [
                    { rule: 'required', message: '数量不能为空' }
                ],
                settlePrice: [
                    { rule: 'required', message: '发包人结算单价不能为空' }
                ],
                contractPrice: [
                    { rule: 'required', message: '招标控制单价不能为空' }
                ]
            }
        }
    },
    watch: {},
    mounted: async function() {
        if (this.state === 3) {
            this.editingKey = true
        }
    },
    methods: {
        async createList(selectRow) {
            this.loading = true
            let data = {
                materialContractId: this.id,
                materialId: selectRow.id
            }
            let res = await cloudBuildNetworkApi.createByDetails(data)
            if (res.code === 200) {
                await this.$refs.table.getData()
            }
            this.loading = false
        },
        openDailog: function() {
            if (this.editingKey !== '') {
                this.$message.error('新增前请结束当前操作行')
                return
            }
            this.$refs.detailDialog.open()
        },
        handleChange(val, row, col) {
            if (col === 'number' || col === 'settlePrice') {
                if (row['number'] && row['settlePrice']) {
                    row['sumSettle'] = Number(row['number']) * Number(row['settlePrice'])
                    row['sumSettle'] =  row['sumSettle'].toFixed(2)
                } else {
                    row['sumSettle'] = 0
                }
            }
            if (col === 'number' || col === 'contractPrice') {
                if (row['number'] && row['contractPrice']) {
                    row['sumTotal'] = Number(row['number']) * Number(row['contractPrice'])
                   row['sumTotal'] =  row['sumTotal'].toFixed(2)
                } else {
                    row['sumTotal'] = 0
                }
            }
            if (col === 'settlePrice' || col === 'contractPrice') {
                if (row['settlePrice'] && row['contractPrice']) {
                    row['sumSettlContractDiff'] = Number(row['settlePrice']) - Number(row['contractPrice'])
                  row['sumSettlContractDiff'] =  row['sumSettlContractDiff'].toFixed(2)
                } else {
                    row['sumSettlContractDiff'] = 0
                }
            }
            if (row['sumSettle'] && row['sumTotal']) {
                row['sumSettleContract'] = Number(row['sumSettle']) - Number(row['sumTotal'])
              row['sumSettleContract'] =  row['sumSettleContract'].toFixed(2)
            }

            if (row['sumSettleContract'] && row['sumSettle']) {
                row['sumUnitPoint'] = Number(row['sumSettleContract']) / ~Number(row['sumSettle'])
                row['sumUnitPoint'] = row['sumUnitPoint'].toFixed(2)
            }
            this.$console(row)
        },
        async save(target) {
            this.$console(target)
            if (target.number === null) {
                return this.$message.warning('数量不能为空')
            }
            if (!target.settlePrice) {
                return this.$message.warning('发包人结算单价不能为空')
            }
            if (!target.contractPrice) {
                return this.$message.warning('合同单价不能为空')
            }
            this.loading = true
            let res
            if (target.id) {
                res = await cloudBuildNetworkApi.editByDetails(target)
            } else {
                res = await cloudBuildNetworkApi.createByMain(target)
            }
            if (res.code === 200) {
                this.$message.success('操作成功')
                this.$emit("getTotal")
                this.cancel()
            }
            this.loading = false
        },
        cancel() {
            this.editingIndex = null
            this.$refs.table.getData()
        }
    }
}
</script>
<style lang="less" scoped>

.ant-form-item-control-wrapper {
    //width: 100% !important;

}
</style>
